package com.hula.onion.book.server.spider.platforms.xiaoniuzaixian;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.JedisUtils;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.config.SysConstants;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import com.hula.onion.book.server.utils.RegexParserUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("xiaoNiuZaiXianSpider")
public class XiaoNiuZaiXianSpider extends SpiderCommon {

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.xiaoniu88.com/user/login";

    /**
     * 验证码URL
     */
    private static final String CAPTCHA_URL = "https://www.xiaoniu88.com/user/captcha";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.xiaoniu88.com/MyAccount/index";

    @Autowired
    private XiaoNiuZaiXianSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {
        try {
            //1. 从缓存中获取cookie，设置到cookie store中
            CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), getHttpContext().getCookieStore());

            //2. 模拟登陆
            String responseStr = HttpUtils.post(LOGIN_URL,
                    spiderHelper.installRequestParams(loginForm),
                    getHttpContext());
            logger.info("[xiaoNiuZaiXianSpider] Http response result:{}", responseStr);

            XiaoNiuZaiXianResponseEntity responseEntity = JSONObject.parseObject(responseStr, XiaoNiuZaiXianResponseEntity.class);

            if ("0".equals(responseEntity.getResultCode())) {
                //2.1 爬取用户详细信息
                String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
                logger.info("[xiaoNiuZaiXianSpider] Http response account result:{}", result);
                //2.2 解析JSON
                return spiderHelper.parseAccountBalance(result);
            } else if ("5".equals(responseEntity.getResultCode())) {
                return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
            }

        } catch (Exception e) {
            logger.error("[xiaoNiuZaiXianSpider] Install request params error!");
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_URL;
    }

    @Override
    public void getIndexPageInfo(String html, int platformId, String userFlag) {

        String beginRegex = "<input type=\"hidden\" id=\"ooh.token.name\" name=\"ooh.token.name\" value=\"";
        String endRegex = "\" />";
        String tokenName = new RegexParserUtils(beginRegex, endRegex, html, RegexParserUtils.TEXTTEGEX).getText();

        beginRegex = "<input type=\"hidden\" id=\"ooh.token.value\" name=\"ooh.token.value\" value=\"";
        endRegex = "\" />";

        String tokenValue = new RegexParserUtils(beginRegex, endRegex, html, RegexParserUtils.TEXTTEGEX).getText();

        String nameKey = SysConstants.REDIS_KEY_PRE + SysConstants.INDEX_PAGE_INFO_PRE + SysConstants.TOKEN_NAME + platformId + ":" + userFlag;
        String valueKey = SysConstants.REDIS_KEY_PRE + SysConstants.INDEX_PAGE_INFO_PRE + SysConstants.TOKEN_VALUE + platformId + ":" + userFlag;

        JedisUtils.getInstance().set(nameKey, tokenName);
        JedisUtils.getInstance().set(valueKey, tokenValue);

    }
}

